package com.dragon.common.netty;

import com.dragon.protoJo.bean.msg.ProtoMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //消息唯一标识这里演示写为msg-sn,正常流程应由服务端返回,这里解析
        String key = "msg-sn";
//        String msgStr = msg.toString();
//        try{
//            //消息唯一标识这里演示写为test-key,正常流程应由服务端返回,这里解析
//            NettyTools.setReceiveMsg(key, msgStr);
//        }catch (Exception e){
//            log.error("消息转码失败:{} ",msg.toString());
//            e.printStackTrace();
//        }
        if (msg == null || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }
        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType headType = message.getType();
        if (!headType.equals(ProtoMsg.HeadType.MESSAGE_RESPONSE)) {
            super.channelRead(ctx, msg);
            return;
        }
        String info = "";
        switch (message.getMessageResponse().getCode()){
            // 正常发送消息了
            case 0:
                info = "0";
                break;
                // 接收人不在线
            case 4:
                info = "1";
                break;
            default:
                throw new Exception(message.getMessageResponse().getInfo());
        }
        // 返回发送成功
        NettyTools.setReceiveMsg(key, info);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("异常:{}", cause.getMessage());
        ctx.fireExceptionCaught(cause);
    }
}
